from rest_framework import serializers
from roomManage import models


class RoomTypeSeriallizer(serializers.ModelSerializer):
    """
    房间类型序列化
    """

    class Meta:
        model = models.RoomType
        fields = '__all__'


class RoomFloorSeriallizer(serializers.ModelSerializer):
    """
    房间楼层序列化
    """

    class Meta:
        model = models.RoomFloor
        fields = '__all__'


class RoomMasterSeriallizer(serializers.ModelSerializer):
    """
    房间序列化
    """
    type_name = serializers.CharField(source='type.name', required=False)
    floor_name = serializers.CharField(source='floor.name', required=False)
    class Meta:
        model = models.RoomMaster
        fields = ['id', 'name', 'uuid', 'type_id', 'type_name', 'floor_id', 'floor_name',
                  'sort', 'status', 'imgPath']

from deviceManage import models as dm
class RoomsSeriallizer(serializers.ModelSerializer):
    """
    首页房间序列化
    """
    type_name = serializers.CharField(source='type.name', required=False)
    floor_name = serializers.CharField(source='floor.name', required=False)
    devicecount = serializers.SerializerMethodField()

    alarm = serializers.SerializerMethodField()

    def get_alarm(self, instance):
        alarm = dm.Alarm.objects.filter(device__room=instance, recovertime=None).count()
        return alarm

    def get_devicecount(self, instance):
        dit = {}
        devices = instance.device_set.filter()
        total = devices.count()
        online = devices.filter(online=1, room__status=1).count()
        offline = total-online
        dit['total'] = total
        dit['online'] = online
        dit['offline'] = offline
        return dit


    class Meta:
        model = models.RoomMaster
        fields = ['id', 'name', 'status', 'imgPath', 'type_name', 'floor_name', 'devicecount', 'alarm']